/*
 * Copyright 2010 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy.anim.impl
{

	internal class SerialAnimation extends AnimationGroupBase
	{

		public function SerialAnimation(manager:AnimationManager, animations:Array)
		{
			super(manager, animations);
		}

		override protected function get animationName():String
		{
			return "Serial";
		}

		override protected function onInitializeInternal():void
		{
			var totalDuration:Number = 0;
			var info:AnimationGroupInfo = _animationInfo;
			var count:int = _numAnimations;
			var last:uint = 0;

			while (--count > -1)
			{
				info.animation.initialize();
				totalDuration += info.animation._duration;
				info.start = last;
				info.end = last + info.animation._duration;
				last = info.end;
				info = info.next;
			}

			_duration = normalizeDuration(totalDuration);
		}

		override protected function onUpdateInternal():void
		{
			var animation:AnimationBase;
			var found:Boolean = false;
			var target:AnimationBase = null;
			var targetPosition:int;
			var count:int = _numAnimations;
			var info:AnimationGroupInfo = _animationInfo;

			while (--count > -1)
			{
				animation = info.animation;
				if (info.start <= _position && _position <= info.end)
				{
					found = true;
					target = animation;
					targetPosition = _position - info.start;
				}
				else if (found)
				{
					if (animation._position !== -1)
					{
						animation.position = -1;
					}
				}
				else
				{
					if (_position > -1)
					{
						if (animation._position !== animation._duration)
						{
							animation.position = animation._duration;
						}
					}
				}

				info = info.next;
			}

			if (target !== null)
			{
				target.position = targetPosition;
			}
			else if (_position === -1 && _numAnimations > 0)
			{
				_animationInfo.animation.position = -1
			}
		}
	}
}
